<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- <pre>{{scope.row}}</pre> -->
            <el-row
              :class="['bdbottom','vcenter',i1==0?'bdtop':'']"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环 -->
                <el-row
                  :class="[i2===0?'':'bdtop','vcenter']"
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editRoles(scope.row.id)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteDialog(scope.row.id)"
            >删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加权限 -->
      <el-dialog title="添加权限" :visible.sync="addDialogVisible" width="30%" @close="addDialogClose">
        <el-form ref="rolesFormRef" :model="rolesFormList" :rules="rolesRules" label-width="80px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="rolesFormList.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="rolesFormList.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addDialog">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑角色 -->
      <el-dialog title="编辑角色" :visible.sync="editDialogVisible" width="30%">
        <el-form
          ref="rolesFormRef"
          :model="editFormList"
          :rules="editRolesRules"
          label-width="80px"
        >
          <el-form-item label="角色名称">
            <el-input v-model="editFormList.roleName" disabled></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editFormList.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editDialog">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配权限的对话框 -->
      <el-dialog
        title="分配权限"
        :visible.sync="SetRightdialogVisible"
        width="30%"
        @close="SetRightClose"
      >
        <!-- 树形空间 -->
        <!-- show-checkbox:节点是否可被选择 -->
        <!-- default-expand-all: 展开所有节点 -->
        <!-- node-key:每个树节点用来作为唯一标识的属性，整棵树应该是唯一的 -->
        <!-- default-checked-keys	默认勾选的节点的 key 的数组   通过该属性把已有的三级权限默认选中状态   -->
        <el-tree
          :data="setRightList"
          :props="defaultProps"
          show-checkbox
          default-expand-all
          node-key="id"
          :default-checked-keys="defaultKeys"
          ref="setRightRef"
        ></el-tree>
        <!-- 对话框底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="SetRightdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      rolesList: [],
      addDialogVisible: false,
      editDialogVisible: false,
      SetRightdialogVisible: false,
      rolesFormList: {
        roleName: '',
        roleDesc: ''
      },
      editFormList: {},
      setRightList: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      defaultKeys: [],
      // 当前即将分配权限的角色id
      // 在showSetRightDialog方法中赋值
      roleid: '',
      rolesRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请填写角色描述', trigger: 'blur' }
        ]
      },
      editRolesRules: {
        roleDesc: [
          { required: true, message: '请填写角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.$message.success('获取角色列表成功')
      this.rolesList = res.data
    },
    // 删除事件  删除三级权限  显示删除确认框
    async removeRightById(role, id) {
      const configResult = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (configResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      // this.getRolesList()
      role.children = res.data
      this.$message.success('删除成功')
    },
    // 提交添加权限
    addDialog() {
      this.$refs.rolesFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.rolesFormList)
        if (res.meta.status !== 201) {
          return this.$message.error('添加失败')
        }
        this.getRolesList()
        this.addDialogVisible = false
        this.this.$message.success('添加成功')
      })
    },
    // 重置表单
    addDialogClose() {
      this.$refs.rolesFormRef.resetFields()
    },
    // 编辑表单 显示文本框
    async editRoles(id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('roles/' + id)
      this.editFormList = res.data
    },
    // 提交编辑角色
    editDialog() {
      this.$refs.rolesFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'roles/' + this.editFormList.roleId,
          {
            roleName: this.editFormList.roleName,
            roleDesc: this.editFormList.roleDesc
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('更新失败')
        }
        this.getRolesList()
        this.editDialogVisible = false
        this.$message.success('更新成功')
      })
    },
    // 删除角色
    async deleteDialog(id) {
      const a = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      if (a !== 'confirm') return
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.getRolesList()
      this.$message.success('删除成功')
    },
    // 展示分配权限的对话框
    async showSetRightDialog(role) {
      // 先获取分配权限列表
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      this.setRightList = res.data
      // 记录 id值
      this.roleid = role.id
      // 递归函数调用
      this.getLeafKeys(role, this.defaultKeys)
      this.SetRightdialogVisible = true
    },
    // 通过递归形式获取角色下的三级权限的id，并保存到defaultKeys数组中
    getLeafKeys(role, arr) {
      // 在展示分配权限的对话框函数中调用该函数
      // role代表当前节点、
      // 该函数会获取到当前角色的所有三级权限id并添加到degaultKeys中
      // 判断当前节点是否包含children，如果不包含就说明是三级权限
      if (!role.children) return arr.push(role.id)
      role.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 关闭分配分配权限对话框时重置表单
    SetRightClose() {
      // 置空数组即可
      this.defaultKeys = []
    },
    // 发起角色授权的请求
    async allotRights() {
      var keys = [
        // 获取全选节点的id
        ...this.$refs.setRightRef.getCheckedKeys(),
        // 获取半选节点id
        ...this.$refs.setRightRef.getHalfCheckedKeys()
      ]
      var idStr = keys.join(',')

      const { data: res } = await this.$http.post(
        `roles/${this.roleid}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('更新失败')
      }
      this.getRolesList()
      this.SetRightdialogVisible = false
    }
  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdbottom {
  border-bottom: 1px solid #ccc;
}
.bdtop {
  border-top: 1px solid #ccc;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
